<template>
<h1>详情页面</h1>
  <h2>{{weibo.nickname}}说:{{weibo.content}}</h2>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <h3>评论相关</h3>
  <el-input placeholder="说点儿啥..." v-model="c.content"></el-input>
  <el-button @click="post()">评论</el-button>
  <div v-for="comment in arr">
    <h4>{{comment.nickname}}评论说:{{comment.content}}
      <span style="font-size: 12px;color: #666">
        发布于:{{comment.created}}</span>
    </h4>
  </div>
</template>
<script setup>
import {onMounted, ref} from "vue";
  import axios from "axios";
import router from "@/router";
import qs from "qs";
import {ElMessage} from "element-plus";
  const c = ref({content:""});
  const post = ()=>{
    let user = localStorage.user?JSON.parse(localStorage.user):null;
    if (user==null){
      alert("请先登录!");
      router.push('/login');
    }
    c.value.userId = user.id;//设置登录用户id为此评论作者id
    c.value.weiboId = weibo.value.id;
    let data = qs.stringify(c.value);
    axios.post('http://localhost:8080/v1/comments/add-new',data)
    .then((response)=>{
      if (response.data.code==2001){
        ElMessage.success("发布完成!");
        c.value.content="";//清空评论框的内容
        loadComments(weibo.value.id);
      }
    })
  }


  const weibo = ref({});
  const arr = ref([]);
  const loadComments = (id)=>{
    axios.get('http://localhost:8080/v1/comments/'+id)
    .then((response)=>{
      if (response.data.code==2001){
        arr.value = response.data.data;
      }
    })
  }
  onMounted(()=>{
    //从地址栏中得到id    location.search=  ?id=xx
    let id = new URLSearchParams(location.search).get('id');
    loadComments(id);
    console.log(id);
    axios.get('http://localhost:8080/v1/weibos/'+id)
        .then((response)=>{
        if (response.data.code==2001){
          weibo.value = response.data.data;
        }
    })
  })
</script>

<style scoped>

</style>